#include"head.h"
// 工作线程用来读取main线程accept的客户端连接对象
int recv_from_main(int local_socket, int *flag, int *net_fd){

   struct msghdr hdr;
   bzero(&hdr, sizeof(hdr));

   // 凑正文信息
   int * num = (int *)malloc(sizeof(int));
   struct iovec iov[1];
   iov[0].iov_base = num;
   iov[0].iov_len = sizeof(int);

   hdr.msg_iov = iov;
   hdr.msg_iovlen = 1;

   // 凑控制信息
   struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
   cms->cmsg_len = CMSG_LEN(sizeof(int));
   cms->cmsg_level = SOL_SOCKET;
   cms->cmsg_type = SCM_RIGHTS;

   hdr.msg_control = cms;
   hdr.msg_controllen = CMSG_LEN(sizeof(int));

   recvmsg(local_socket, &hdr, 0);

   void *p = CMSG_DATA(cms);
   *net_fd = *(int *)p;

   *flag = *num;
   return  0;
}


// main进程accept获得的客户端连接对象发送给工作进程
int write_net_fd(int local_socket, int* netfd, int flag){

   struct msghdr hdr;
   bzero(&hdr, sizeof(hdr));

   // 凑正文信息
   struct iovec iov[1];
   iov[0].iov_base = &flag;
   iov[0].iov_len = sizeof(int);

   hdr.msg_iov = iov;
   hdr.msg_iovlen = 1;

   // 凑控制信息
   struct cmsghdr *cms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
   cms->cmsg_len = CMSG_LEN(sizeof(int));
   cms->cmsg_level = SOL_SOCKET;
   cms->cmsg_type = SCM_RIGHTS;

   void *p = CMSG_DATA(cms);
   int *num = (int *)p;
   *num = *netfd;
   if(flag==0)
   {
       printf("now:write:-----flag=0:local.c:pid:%d   local_socket:%d\n",getpid(),local_socket);
   }
   else
   {
       printf("now---num=-1:write:local.c:pid:%d   local_socket:%d\n",getpid(),local_socket);
   }

   hdr.msg_control = cms;
   hdr.msg_controllen = CMSG_LEN(sizeof(int));

   sendmsg(local_socket, &hdr, 0);

   return 0;

}
